/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package digitaldreamers.games.papermonsters.clients.gameclient.gameui.gamescreens;

import digitaldreamers.games.papermonsters.clients.gameclient.gameui.PaperMonsters;
import digitaldreamers.libraries.games.clients.networkmanagement.abstracts.IConnectionHandler.OnDataReceivedListener;
import digitaldreamers.libraries.games.clients.networkmanagement.concrete.ConnectionHandler;
import digitaldreamers.libraries.games.clients.gameclient.gameui.implementation.RenderPanel;
import digitaldreamers.libraries.games.clients.gameclient.gameui.implementation.GameScreen;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author Dao Le
 */
public abstract class AbNetworkScreen extends GameScreen implements Runnable, OnDataReceivedListener {
    protected static final int SLEEP_TIME = 100;
    
    private ArrayList<byte[]> m_DataQueue = null;
    private Thread m_PacketHandleThread = null;
    private volatile boolean m_bIsRunning = false;
    protected ConnectionHandler m_ConnectionHandler = null;
    
    public AbNetworkScreen(RenderPanel renderPanel) {
        this(renderPanel.getWidth(), renderPanel.getHeight(), renderPanel);
    }
    
    public AbNetworkScreen(int iScreenWidth, int iScreenHeight, RenderPanel renderPanel) {
        super(iScreenWidth, iScreenHeight, renderPanel);
        m_DataQueue = new ArrayList();
        m_ConnectionHandler = ((PaperMonsters)m_Game).getConnectionHandler();
        m_ConnectionHandler.addEventListener(this);
        m_PacketHandleThread = new Thread(this);
        m_PacketHandleThread.start();
        m_bIsRunning = true;
    }
    
    public synchronized void addPacket(byte[] arr_byData) {
        m_DataQueue.add(arr_byData);
    }
    
    public synchronized void removePacket(int iIndex) {
        m_DataQueue.remove(iIndex);
    }
    
    public synchronized byte[] getPacket(int iIndex) {
        return m_DataQueue.get(iIndex);
    }
    
    @Override
    public void onDataReceived(byte[] arr_byData) throws IOException {
        addPacket(arr_byData);
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (m_bIsRunning) {
            if (m_DataQueue.size() > 0) {
                byte[] data = getPacket(0);
                removePacket(0);
                try {
                    handlePacket(data);
                } catch (Exception ex) {
                }
            }
            try {
                Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException ex) {
            }
        }
    }
    
    public abstract void handlePacket(byte[] data) throws Exception;
}
